﻿using System;
using System.ComponentModel;
using System.IO;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Gmantis.Imaging;

namespace Gmantis.Controls.Chart.Extended
{
    public enum ImageFormat
    {
        Jpeg,
        Png
    }

    [EditorBrowsable(EditorBrowsableState.Never)]
    public static class ImageExport
    {
        // Methods
        public static void SaveImage(this Chart chart, Stream stream, ImageFormat imageFormat, Brush background = null)
        {
            if (chart == null)
            {
                throw new ArgumentNullException("chart");
            }
            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }
            int actualWidth = (int)chart.ActualWidth;
            int actualHeight = (int)chart.ActualHeight;
            WriteableBitmap writeableBitmap = new WriteableBitmap(actualWidth, actualHeight);
            if (background != null)
            {
                Canvas element = new Canvas
                {
                    Width = actualWidth,
                    Height = actualHeight,
                    Background = background
                };
                writeableBitmap.Render(element, null);
            }
            writeableBitmap.Render(chart, null);
            writeableBitmap.Invalidate();
            Bitmap bmp = new Bitmap(writeableBitmap);
            Stream stream2 = null;
            switch (imageFormat)
            {
                case ImageFormat.Jpeg:
                    stream2 = JpgCodec.Encode(bmp);
                    break;

                case ImageFormat.Png:
                    stream2 = PngCodec.Encode(bmp);
                    break;
            }
            if (stream2 != null)
            {
                byte[] buffer = new byte[stream2.Length];
                stream2.Read(buffer, 0, buffer.Length);
                stream.Write(buffer, 0, buffer.Length);
            }
        }
    }
}
